package at.fhooe.im440.pandora.entities;

import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;

import at.fhooe.im440.pandora.core.Core;

public class EntityManager {

	private Map<String, Entity> objects;

	@SuppressWarnings("unused")
	private Core core;

	private EntityQueue entityQueue;
	private boolean refreshRenderLayersOnUpdate = false;;

	public EntityManager(Core core) {
		this.core = core;
		this.objects = new TreeMap<String, Entity>();
		this.entityQueue = new EntityQueue();

	}

	public void addEntity(Entity e) {
		entityQueue.queueEntityAdd(e);
	}

	public void removeEntity(Entity e) {
		entityQueue.queueEntityRemove(e);
	}

	public Entity getEntity(String name) {

		Object[] keySet = objects.keySet().toArray();

		int prefixLen = Entity.getLayerPrefixLength();
		int stringLen = name.length();

		for (Object key : keySet) {
			if (((String) key).substring(prefixLen, prefixLen + stringLen)
					.contains(name)) {
				return objects.get(key);
			}
		}

		return null;

	}

	

	public ArrayList<Entity> getEntityWithNameLike(String name) {
		ArrayList<Entity> returnList = new ArrayList<Entity>();
		Object[] keySet = objects.keySet().toArray();

		int prefixLen = Entity.getLayerPrefixLength();

		for (Object key : keySet) {
			if (((String) key).substring(prefixLen).contains(name)) {
				returnList.add(objects.get(key));
			}
		}
		return returnList;
	}

	private void refreshRenderLayers() {

		Collection<Entity> tempEntities = objects.values();
		this.objects = new TreeMap<String, Entity>();

		for (Entity e : tempEntities) {
			objects.put(e.getNameWithLayer(), e);
		}

	}

	public void requestRenderLayerUpdate() {
		refreshRenderLayersOnUpdate = true;
	}

	public void updateAllEntities() {
		if(!core.isPaused()) {
			entityQueue.process(objects);
			entityQueue.entitiesToAdd.clear();
			//entityQueue.entitiesToRemove.clear();
	
			for (Entity ent : objects.values()) {
				ent.update();
			}
	
			if (refreshRenderLayersOnUpdate) {
				refreshRenderLayers();
				refreshRenderLayersOnUpdate = false;
			}
		}
	}

	public void renderAllEntities(Graphics2D g) {

		for (Entity ent : objects.values()) {
			ent.render(g);
		}

	}

}
